const searchBar = document.querySelector("#search-books input")
const list = document.querySelector("#book-list ul")
const addForm = document.querySelector("form#add-book");
const hideBox = document.querySelector("#hide")
const tab_buttons = document.querySelector(".tab-buttons")
const tab_lis = document.querySelectorAll(".tab-buttons li")
const tab_contents = document.querySelectorAll(".tab-content")

//阅读清单数组
var booksArray = JSON.parse(localStorage.getItem('book-list')) || []

//保存阅读清单数据函数
function saveToLocalStorage(data) {
    localStorage.setItem('book-list', JSON.stringify(data))
}

//添加新书籍到数组
function addBook(book_name) {
    booksArray.push({
        id: Date.now(),
        hide: false,
        title: book_name,
    })
    //保存到本地数据库
    saveToLocalStorage(booksArray)
    
    renderBookList(booksArray)
}

//删除书籍函数
function deleteBook(id){
    booksArray = booksArray.filter(book =>{
        return book.id !== id
    })
    //保存到本地数据库
    saveToLocalStorage(booksArray)

    renderBookList(booksArray)
}

//渲染清单函数
function renderBookList(books) {
    list.innerHTML = ""

    books.forEach(book=>{
        const BookItemHTML = `
            <li data-id="${book.id}"
                style="display: ${ book.hide ? "none": "flex" }">
                <span class="name"> ${ book.title } </span>
                <span class="delete" data-id="${book.id}">删除</span>
            </li>
            `
        list.insertAdjacentHTML("beforeend", BookItemHTML)
    })
}

function bindEvents() {
    
    //新增书籍
    addForm.addEventListener("submit", (event) => {
        console.log('submit')
        //停止默认的表单提交
        event.preventDefault();

        //获取输入框对象，在 addForm 对象中找 input
        const bookInputEle = document.querySelector("form#add-book input[type='text']");
        //const bookInputEle = addForm.querySelector("input[type='text']");
        //获取输入框内容
        const bookName = bookInputEle.value.trim();
        if (!bookName) return;
        
        addBook(bookName)

        bookInputEle.value = ""
    })

    //书籍删除
    list.addEventListener("click", (event)=>{
        const id = Number(event.target.dataset.id)
        if(event.target.classList.contains("delete")) {
            deleteBook(id)
        }
    })

    //搜索书籍
    searchBar.addEventListener("keyup", (event) => {
        
        const searchTitle = event.target.value
    
        //过滤了符合条件的书籍
        const searchBooks = booksArray.filter((book)=> {
            return book.title.toLowerCase().indexOf(searchTitle) > -1
        });
        
        //调用渲染函数，传入符合条件的书籍
        renderBookList(searchBooks.length > 0 ? searchBooks: booksArray);
    })

}

//隐藏书籍
hideBox.addEventListener("change", (event)=>{
    console.log(event)
    //event.target.checked
    list.style.display = event.target.checked ? "none" : "initial"
})

//标签页切换
tab_lis.forEach(button => {
    button.addEventListener('click', function() {
        // 3. 获取当前点击标签的数据属性值
        const targetTabId = this.getAttribute('data-target');

        // 4. 移除所有标签和面板的 'active' 类
        tab_lis.forEach(btn => btn.classList.remove('active'));
        tab_contents.forEach(panel => panel.classList.remove('active'));

        // 5. 为当前点击的标签添加 'active' 类
        this.classList.add('active');

        // 6. 找到对应的内容面板并添加 'active' 类
        const targetPanel = document.querySelector(targetTabId);
        if (targetPanel) {
            targetPanel.classList.add('active');
        }
    });
});

renderBookList(booksArray)
bindEvents()